from google.appengine.ext import db

from xml.dom import minidom


class MobileMessage(db.Model):
    source = db.StringProperty()
    target = db.StringProperty()
    messageType = db.StringProperty()

class Sms(MobileMessage):
    msg = db.StringProperty()
    id = db.StringProperty()
    udh = db.StringProperty()

class Mms(MobileMessage):
    subject = db.StringProperty()
    files = db.StringListProperty()

class GlobeXmlLog(db.Model):
    xml = db.StringProperty()
    accepted_at = db.DateTimeProperty(auto_now_add=True)


def parseMessage(xml):
    dom = minidom.parseString(xml)

    gxml = GlobeXmlLog(xml = dom.toxml())
    gxml.put()

    message = {}
    for node in dom.getElementsByTagName('param'):
        name = node.getElementsByTagName('name')[0].firstChild.data
        valueTag = node.getElementsByTagName('value')[0]
        value = None
        if valueTag.firstChild:
            value = valueTag.firstChild.data
        message[name] = value

    message_obj = None
    if message['messageType'] == 'SMS':
        message_obj = Sms(
                          source = message['source'],
                          target = message['target'],
                          messageType = message['messageType'],
                          msg = message['msg'].decode('string_escape'),
                          id = message['id'],
                          udh = message['udh']
                          )
    # experimental
    elif message['messageType'] == 'MMS':
        file_list = []
        files = message['file'].getElementsByTagName('file')
        for f in files:
            file_list.append(f.something)
        message_obj = Mms(
                          source = message['source'],
                          target = message['target'],
                          messageType = message['messageType'],
                          subject = message['subject'].decode('string_escape'),
                          files = file_list
                          )
    return message_obj
